package com.taobao.demo.common.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录用户工具类：从Token中获取当前登录用户ID（商家ID即用户ID）
 */
public class LoginUserUtil {

    private static JwtUtil jwtUtil = SpringContextUtil.getBean(JwtUtil.class); // 从Spring容器获取JwtUtil

    /**
     * 获取当前登录用户ID（商家ID = 用户ID，仅在MERCHANT角色接口中调用）
     */
    public static Long getCurrentUserId() {
        // 1. 从当前请求中获取Token
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new RuntimeException("无法获取当前请求");
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new RuntimeException("请求头缺少有效Token");
        }
        String token = authHeader.substring(7);

        // 2. 解析Token获取用户ID（商家ID即用户ID）
        return jwtUtil.getUserIdFromToken(token);
    }

    /**
     * 简化：直接获取当前登录商家ID（与用户ID一致，语义化命名）
     */
    public static Long getCurrentMerchantId() {
        return getCurrentUserId(); // 商家ID = 用户ID，直接复用
    }
}